<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="80px" size="mini">
      <el-form-item label="退换单号" prop="saleReturnOdd">
        <el-input v-model="queryParams.saleReturnOdd" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.params.customerName" clearable placeholder="请输入"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" placeholder="请选择">
          <el-option key="待审核" :value="1" label="待审核"></el-option>
          <el-option key="被驳回" :value="2" label="被驳回"></el-option>
          <el-option key="已退货" :value="3" label="已退货"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="dateRange" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期" style="width: 240px" type="daterange" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpSaleReturn:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">新增销售退换货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpSaleReturn:export']" icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">列表导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ErpSaleReturnList" row-key="saleReturnId" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="50" align="center" :reserve-selection="true"/>
      <el-table-column align="center" label="退换货单号" prop="saleReturnOdd" sortable/>
      <el-table-column align="center" label="销售单号" prop="saleOdd" sortable/>
      <el-table-column align="center" label="客户名称" prop="customerName"/>
      <el-table-column align="center" label="销售人" prop="salePersonName" width="120"/>
      <el-table-column align="center" label="退换货数量" prop="outNumber" sortable width="120"/>
      <el-table-column align="center" label="退换货总额" prop="returnPrice" sortable width="180">
        <template slot-scope="scope">
          <span>{{ formattedNumber(scope.row.returnPrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="approveStatus" sortable width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approveStatus == 1" type="info">待审批</el-tag>
          <el-tag v-if="scope.row.approveStatus == 2" type="danger">被驳回</el-tag>
          <el-tag v-if="scope.row.approveStatus == 3" type="success">已退货</el-tag>
          <el-tooltip v-if="scope.row.approveStatus == 2" effect="light" placement="bottom">
            <div slot="content">
              {{ scope.row.rejectReason }}
            </div>
            <i class="el-icon-warning-outline" style="margin-left: 5px; color: red"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审批人" prop="approveName" width="120"/>
      <el-table-column align="center" label="审批时间" prop="approveTime" sortable width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="createName" width="120"/>
      <el-table-column align="center" label="创建时间" prop="createTime" sortable width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="120">
        <template slot-scope="scope">
          <el-button v-if="scope.row.approveStatus == 1" v-hasPermi="['erp:ErpSaleReturn:audit']"  size="mini" type="text" @click="handleViewOrAudit(scope.row, 2)">审核</el-button>
          <el-button v-if="scope.row.approveStatus == 2" v-hasPermi="['erp:ErpSaleReturn:edit']"  size="mini" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-hasPermi="['erp:ErpSaleReturn:view']"  size="mini" type="text" @click="handleViewOrAudit(scope.row, 1)">查看</el-button>
          <el-button v-if="scope.row.approveStatus == 3" v-hasPermi="['erp:ErpSaleReturn:print']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 3)">打印</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 审核or预览 -->
    <el-dialog :title="viewAuditTitle" :visible.sync="isAuditOrViewOpen" append-to-body width="80%">
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <div id="printXSForm">
          <div class="title">湖南三才环境科技有限公司（销售退换货单）</div>
          <div class="head-print">
            <div>退换货单号：{{ form.saleReturnOdd }}</div>
            <div>销售单号：{{ form.saleOdd }}</div>
            <div>销售日期：{{ parseTime(form.saleTime, "{y}年{m}月{d}日") }}</div>
            <div>销售人：{{ form.salePersonName }}</div>
            <div>审核人：{{ form.approveName }}</div>
          </div>
          <div class="head-print">
            <div>客户名称：{{ form.customerName }}</div>
            <div>联系人：{{ form.linkman }}</div>
            <div>联系电话：{{ form.linkmanPhone }}</div>
            <div>客户地址：{{ form.address }}</div>
          </div>
          <right-toolbar :columns="columns" :refresh="false" :search="false" class="no-print"></right-toolbar>
          <table class="table_print">
            <tr>
              <th v-if="columns[0].visible" width="80px">序号</th>
              <th v-if="columns[1].visible">商品编号</th>
              <th v-if="columns[2].visible">商品名称</th>
              <th v-if="columns[3].visible">商品类别</th>
              <th v-if="columns[4].visible">规格</th>
              <th v-if="columns[5].visible">单位</th>
              <th v-if="columns[6].visible">单位关系</th>
              <th v-if="columns[11].visible">退换方式</th>
              <th v-if="columns[9].visible">退换数量</th>
              <th v-if="columns[7].visible">成本总价</th>
              <th v-if="columns[8].visible">退货单价</th>
              <th v-if="columns[10].visible">退货总额</th>
            </tr>
            <tr v-for="(item,index) in form.detailsList" :key="index">
              <td v-if="columns[0].visible">{{index + 1}}</td>
              <td v-if="columns[1].visible">{{item.commodityNo}}</td>
              <td v-if="columns[2].visible">{{item.commodityName1}}</td>
              <td v-if="columns[3].visible">{{item.commodityTypeName}}</td>
              <td v-if="columns[4].visible">{{item.commoditySpec}}</td>
              <td v-if="columns[5].visible">{{item.unitName1}}</td>
              <td v-if="columns[6].visible">{{item.unitRelationship}}</td>
              <td v-if="columns[11].visible">{{item.returnCommodityType == 1 ? '退' : '换'}}</td>
              <td v-if="columns[9].visible">{{item.commodityNumber }}</td>
              <td v-if="columns[7].visible">{{formattedNumber(item.unitResult * item.costPrice)}}</td>
              <td v-if="columns[8].visible">{{formattedNumber(item.salePrice)}}</td>
              <td v-if="columns[10].visible">{{formattedNumber(item.saleMoney) }}</td>
            </tr>
          </table>
          <div class="bottom-print">
            <div>物流费用：{{ formattedNumber(form.logisticsCost) }} / {{ form.logisticsMethod == 1 ? "按重量" : "按体积" }}</div>
            <div>其他费用：{{ formattedNumber(form.otherCost) }} /
              {{ form.otherMethod == 1 ? "按重量" : "按体积" }}</div>
            <div>合计数量：{{ form.sumNumber }}</div>
            <div>退货金额：{{  formattedNumber(form.returnPrice) }}</div>
            <!-- <div v-if="columns[11].visible">销售利润：{{  formattedNumber(form.rateMoney) }}</div> -->
          </div>
          <div class="single-line-print">制单人：{{ $store.getters.nickName}}</div>
          <div class="single-line-print">单据备注：{{ form.remark }}</div><br/>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(3)">通过</el-button>
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(2)">驳回</el-button>
        <el-button v-if="type == 3" v-print="'#printXSForm'" type="primary">打印</el-button>
        <el-button @click="isAuditOrViewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {auditErpSaleReturn, getErpSaleReturn, listErpSaleReturn} from "@/api/erp/ErpSaleReturn";
import {formattedNumber} from "../../../utils/ruoyi";

export default {
  name: "ErpSaleReturn",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 多选ids
      ids: [],
      // 销售退换货表格数据
      ErpSaleReturnList: [],
      // 日期范围
      dateRange: [],
      // 是否显示弹出层
      isAuditOrViewOpen: false,
      viewAuditTitle: '',
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        saleReturnOdd: null,
        approveStatus: null,
        params: {
          customerName: null,
        },
      },
      // 打印列
      columns: [
        { key: 0, label: `序号`, visible: true },
        { key: 1, label: `商品编号`, visible: true },
        { key: 2, label: `商品名称`, visible: true },
        { key: 3, label: `商品类别`, visible: true },
        { key: 4, label: `规格`, visible: true },
        { key: 5, label: `单位`, visible: true },
        { key: 6, label: `单位关系`, visible: true },
        { key: 7, label: `成本价`, visible: true },
        { key: 8, label: `退货单价`, visible: true },
        { key: 9, label: `退换数量`, visible: true },
        { key: 10, label: `退货总额`, visible: true },
        { key: 11, label: `退换方式`, visible: true },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formattedNumber,
    /** 查询销售退换货列表 */
    getList() {
      this.loading = true;
      listErpSaleReturn(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((response) => {
        this.ErpSaleReturnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        saleReturnId: null,
        saleReturnOdd: 'XST' + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        saleId: null,
        saleOdd: null,
        wareId: null,
        returnStatus: null,
        returnPrice: null,
        remark: null,
        logisticsCost: null,
        logisticsMethod: 1,
        otherCost: null,
        otherMethod: 1,
        paymentMethod: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveStatus: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null,
        detailsList: [],
        saleDetailsList: [],
        saleReturnDetailsList: []
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.saleReturnId)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.params.customerName = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/ErpSaleReturn/add-saleReturn/saleReturn/0");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push(
        "/ErpSaleReturn/add-saleReturn/saleReturn/" + row.saleReturnId
      );
    },
    // 查看详情 / 审核
    handleViewOrAudit(row, type) {
      getErpSaleReturn(row.saleReturnId).then(res => {
        this.form = res.data;
        this.form.sumNumber = 0;
        res.data.detailsList.forEach(i => {
          this.form.sumNumber += i.commodityNumber;
          // 退货金额
          i.saleMoney = i.commodityNumber * i.salePrice;
        })
        this.viewAuditTitle = '退换货单：' + this.form.saleReturnOdd;
        this.type = type;
        this.isAuditOrViewOpen = true;
      })
    },
    // 审核
    handleAuditOptions(approveStatus) {
      this.form.approveStatus = approveStatus;
      if (approveStatus == 2) {
        this.$prompt('', '驳回原因', {
          center: true,
          inputType: 'textarea',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          this.form.rejectReason = value;
          this.handleAudit();
        })
      } else {
        this.handleAudit();
      }
    },
    // 审核
    handleAudit() {
      auditErpSaleReturn({
        saleReturnId: this.form.saleReturnId,
        approveStatus: this.form.approveStatus,
        rejectReason: this.form.rejectReason
      }).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.isAuditOrViewOpen = false;
        this.getList();
      })
    },
    // 交易方式格式化
    payConversion(type) {
      let text = '';
      switch (type) {
        case 1:
          text = '现金';
          break;
        case 2:
          text = '微信';
          break;
        case 3:
          text = '支付宝';
          break;
        case 4:
          text = '银行转账';
          break;
      }
      return text;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "erp/ErpSaleReturn/export",
        {
          ...this.queryParams,
          exportIds: this.ids?.join(',')
        },
        `销售退换货_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.title {
  padding: 10px;
  text-align: center;
  font-size: 32px;
  font-weight: 500;
}

.oddInfo {
  font-size: 16px;
}

.remark {
  padding-top: 10px;
  padding-bottom: 10px;
}

table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
